local juyi = fk.CreateSkill{
  name = "reminiscence__juyi",
  tags = {Skill.Limited}
}

local juyi_mark = "@reminiscence__juyi-turn"

Fk:loadTranslationTable{
  ["reminiscence__juyi"] = "举义",
  [":reminiscence__juyi"] = "限定技，结束阶段，若你为手牌上限最大的角色，你可以于本回合结束后进行一个额外的回合，"
  .."将X分配给这个额外回合的摸牌阶段摸牌数、使用【杀】的次数上限（X为你的手牌上限）。",

  ["#reminiscence__juyi-draw"] = "举义：选择分配到摸牌阶段摸牌数的值（至多%arg）<br/>余下分配到使用【杀】的次数上限",
  [juyi_mark] = "举义",

  ["$reminiscence__juyi1"] = "司马氏篡权,我当替天伐之!",
  ["$reminiscence__juyi2"] = "定当移司马氏三族！",
}

juyi:addEffect(fk.EventPhaseStart, {
  anim_type = "big",
  can_trigger = function (self, event, target, player, data)
    if player:usedSkillTimes(juyi.name, Player.HistoryGame) > 0 then return false end
    if player == target and player:hasSkill(juyi.name)
    and player.phase == Player.Finish then
      local room = player.room
      return not table.find(room:getAlivePlayers(false), function (p)
        return p:getMaxCards() > player:getMaxCards()
      end)
    end
  end,
  on_use = function (self, event, target, player, data)
    player:gainAnExtraTurn(true, juyi.name)
  end,
})

juyi:addEffect(fk.TurnStart, {
  mute = true,
  can_trigger = function (self, event, target, player, data)
    return player == target and player:getCurrentExtraTurnReason() == juyi.name
  end,
  on_trigger = function (self, event, target, player, data)
    local room = player.room
    local n = player:getMaxCards()
    local _, ret = room:askToUseActiveSkill(player, {
      skill_name = juyi.name.."_opt",
      prompt = "#reminiscence__juyi-draw:::"..n,
      cancelable = false,
      extra_data = { n = n },
    })
    if ret and ret.interaction then
      local draw_n = ret.interaction
      room:setPlayerMark(player, juyi_mark, {draw_n, n - draw_n})
    end
  end,
})

juyi:addEffect(fk.DrawNCards, {
  mute = true,
  can_trigger = function (self, event, target, player, data)
    return player == target
  end,
  on_trigger = function (self, event, target, player, data)
    local mark = player:getTableMark(juyi_mark)
    if mark[1] and type(mark[1]) == "number" then
      data.n = mark[1]
    end
  end,
})

juyi:addEffect("targetmod", {
  residue_func = function (self, player, skill, scope)
    if skill.trueName == "slash_skill" and scope == Player.HistoryPhase
    and player.phase == Player.Play then
      local mark = player:getTableMark(juyi_mark)
      if mark[2] and type(mark[2]) == "number" then
        return mark[2]
      end
    end
  end
})

return juyi